package com.wind.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.wind.constant.OrderStatusConst;
import com.wind.dao.OrderMapper;
import com.wind.dto.req.OrderReqDto;
import com.wind.entity.Order;
import com.wind.entity.Users;
import com.wind.service.IOrderService;
import com.wind.service.IUsersService;
import com.wind.util.CommonConst;
import com.wind.util.OrderNumEngender;
import com.wind.util.TXSMSUtil;
import com.wind.vo.ResultData;
import com.wind.vo.ResultDataGenerator;
import com.wind.wx.PayCommonUtil;
import com.wind.wx.WXAppletUserInfo;
import com.wind.wx.WeiXinConfig;
import com.wind.wx.Weipayment;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * @ClassName OrderController
 * @Description Hey, it's compiled! Pack it!
 * @Author Administrator
 * @Date 2021/5/29 22:00
 * @Version 1.0
 */
@Api(tags = "订单相关接口")
@RequestMapping("/order")
@RestController
public class OrderController {

    @Resource
    IOrderService orderService;

    @Resource
    IUsersService usersService;

    @ApiOperation("创建订单")
    @PostMapping("/createOrder")
    public ResultData<Long> createOrder(@RequestBody OrderReqDto orderReqDto){
        if(Objects.isNull(orderReqDto.getUserId())){
            return ResultDataGenerator.genFailResult(null, "用户id为空，请先登录");
        }
        //通过验证码判断用户是否是第一次下单
        if(Objects.nonNull(orderReqDto.getCode())){
            String serverCode = TXSMSUtil.get(orderReqDto.getPhone());
            if(!orderReqDto.getCode().equals(serverCode)){
                return ResultDataGenerator.genFailResult(null, "验证码错误");
            }
            // 第一次下单 完善用户信息
            Users user = new Users();
            user.setId(orderReqDto.getUserId());
            BeanUtil.copyProperties(orderReqDto, user);
            usersService.updateById(user);
        }
        Order order = new Order();
        BeanUtil.copyProperties(orderReqDto, order);
        order.setOrderStatus(OrderStatusConst.NON_PAID);
        boolean result = orderService.insert(order);
        if(!result){
            return ResultDataGenerator.genExceptionResult(order.getId(), "下单失败");
        }
        return ResultDataGenerator.genSuccessResult(order.getId(), "下单成功");
    }

    @ApiOperation("微信支付")
    @PostMapping("/wxPay")
    public ResultData<Map<String, Object>> wxPay(@RequestParam("code") String code,
                                                 @RequestParam("userId") Long userId,
                                                 @RequestParam("orderId") Long orderId){
        Wrapper<Users> usersWrapper = new EntityWrapper<>();
        usersWrapper.eq("id", userId);
        Users user = usersService.selectOne(usersWrapper);
        String openId = user.getOpenId();
        if(Objects.isNull(openId) && StrUtil.isNotBlank(code)){
            JSONObject jsonObject = WXAppletUserInfo.putSmallRoutine(code);
            if(Objects.isNull(jsonObject)){
                return ResultDataGenerator.genFailResult(jsonObject, "获取openId失败");
            }
            openId = jsonObject.getString("openid");
        }
        Order order = orderService.selectById(orderId);
        String orderNo = OrderNumEngender.getOrderNum();
        order.setOrderNo(orderNo);
        orderService.updateById(order);
        int price100 = order.getMoney().multiply(new BigDecimal(100)).intValue();
        String nonceStr = PayCommonUtil.CreateNoncestr();
        Map<String, String> t = Weipayment.doProcessPost(WeiXinConfig.JSAPI_ID, openId, "JSAPI", WeiXinConfig.IP, price100, orderNo);
        System.out.println("t->" + t);
        SortedMap<String, Object> reMap = new TreeMap<>();
        Integer time = (int)(new Date().getTime()/1000);
        reMap.put("appId", WeiXinConfig.JSAPI_ID);
        reMap.put("nonceStr", nonceStr);
        reMap.put("package", "prepay_id=" + t.get("prepay_id"));
        reMap.put("signType", "MD5");
        reMap.put("timeStamp", time+"");
        String sign = PayCommonUtil.createSign(CommonConst.CHARSET_UTF8, reMap, WeiXinConfig.API_KEY);

        Map<String, Object> retval = new HashMap<String, Object>();
        retval.put("timeStamp", time+"");
        retval.put("nonceStr", nonceStr);
        retval.put("package", "prepay_id="+t.get("prepay_id"));
        retval.put("signType", "MD5");
        retval.put("paySign", sign);

        return ResultDataGenerator.genSuccessResult(retval, "拉起支付成功");
    }


}
